package cn.dida.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpClientUtil {
	public static Logger logger = Logger.getLogger(HttpClientUtil.class);
	private static final Log loger = LogFactory.getLog(HttpClientUtil.class);

	/**
	 * HTTP Client Object,used HttpClient Class before(version 3.x),but now the
	 * HttpClient is an interface
	 */
	private DefaultHttpClient client;

	public String XML_HEADER = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";

	public static void main(String[] args) throws UnsupportedEncodingException {
		String xml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
				+ "<return_msg><![CDATA[参数错误:send_name字段必填，并且少于32字符]]></return_msg>"
				+ "<result_code><![CDATA[FAIL]]></result_code>" + "<err_code><![CDATA[PARAM_ERROR]]></err_code>"
				+ "<err_code_des><![CDATA[参数错误:send_name字段必填，并且少于32字符]]></err_code_des>"
				+ "<mch_billno><![CDATA[1356931302201612019999999999]]></mch_billno>"
				+ "<mch_id><![CDATA[1356931302]]></mch_id>" + "<wxappid><![CDATA[wxf75ff9d6ace8f97e]]></wxappid>"
				+ "<re_openid><![CDATA[oI4wcsx15bNXKZNTb4wU4eaab8wA]]></re_openid>" + "<total_amount>100</total_amount>"
				+ "</xml>";

		// System.out.println(readStringXml(xml));
	}

	public static String HttpPostWithJson(String url, String json) {
		String returnValue = "这是默认返回值，接口调用失败";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//ResponseHandler<String> responseHandler = new BasicResponseHandler();
		try {
			// 第一步：创建HttpClient对象
			httpClient = HttpClients.createDefault();

			// 第二步：创建httpPost对象
			HttpPost httpPost = new HttpPost(url);

			// 第三步：给httpPost设置JSON格式的参数
			StringEntity requestEntity = new StringEntity(json, "UTF-8");
			requestEntity.setContentEncoding("UTF-8");
			httpPost.setHeader("Content-type", "application/json");
			httpPost.setEntity(requestEntity);
			RequestConfig requestConfig = RequestConfig.custom()  
			        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
			        .setSocketTimeout(5000).build(); 
			httpPost.setConfig(requestConfig);
			// 第四步：发送HttpPost请求，获取返回值
			HttpResponse  responseHandler = httpClient.execute(httpPost); // 调接口获取返回值时，必须用此方法
			HttpEntity entity = responseHandler.getEntity();
			returnValue = EntityUtils.toString(entity , "UTF-8");
					
			// System.out.println("returnValue" + returnValue);
			// CloseableHttpResponse httpResonse = httpClient.execute(httpPost);
			// int statusCode = httpResonse.getStatusLine().getStatusCode();
			// if(statusCode!=200)
			// {
			// System.out.println("请求发送失败，失败的返回参数为："+httpResonse.getStatusLine());
			// returnValue = httpResonse.getStatusLine().toString();
			// }
			//

		} catch (Exception e) {
			//e.printStackTrace();
			return e.getMessage();
			
		}

		finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 第五步：处理返回值
		return returnValue;
	}

	public static String requestPost(String url, Map<String, Object> simpleRequestParamMap)
			throws ClientProtocolException, IOException {

		List<NameValuePair> params = new ArrayList<NameValuePair>();

		for (String key : simpleRequestParamMap.keySet()) {

			Object value = simpleRequestParamMap.get(key);
			if (value != null) {
				params.add(new BasicNameValuePair(key, value.toString()));

			}
		}

		CloseableHttpClient httpclient = HttpClientBuilder.create().build();

		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(new UrlEncodedFormEntity(params));

		CloseableHttpResponse response = httpclient.execute(httppost);
//		System.out.println(response.toString());

		HttpEntity entity = response.getEntity();
		String jsonStr = EntityUtils.toString(entity, "utf-8");
//		System.out.println(jsonStr);

		httppost.releaseConnection();
		return jsonStr;
	}

	public static String post(String url, Map<String, Object> simpleRequestParamMap) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpUriRequest method = new HttpPost(url);
			HttpPost post = (HttpPost) method;
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();

			for (String key : simpleRequestParamMap.keySet()) {

				Object value = simpleRequestParamMap.get(key);
				if (value != null) {
					// if ("sign".equals(key)) {
					// nvps.add(new BasicNameValuePair(key, value.toString()));
					// }else {
					// nvps.add(new BasicNameValuePair(key,
					// URLEncoder.encode(value.toString(),"UTF-8")));
					// }
					nvps.add(new BasicNameValuePair(key, value.toString()));

				}
			}

			post.setEntity(new UrlEncodedFormEntity(nvps));

			HttpParams httpParams = method.getParams();
			httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
			httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
			HttpResponse proxyResponse = client.execute(method);
			String content = EntityUtils.toString(proxyResponse.getEntity());
			return content;
		} catch (Exception e) {
			// ExceptionUtil.logerErrorMes(loger, e);
		}
		return null;
	}
	
	private static HttpPost postForm(String url, Map<String, Object> params) {

		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
		}

		try {
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return httpost;
	}

	public static String get(String url) {

		try {
			HttpClient client = new DefaultHttpClient();
			HttpUriRequest method = new HttpGet(url);

			HttpParams httpParams = method.getParams();
			// httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
			// "GBK");
			httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
			httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
			HttpResponse proxyResponse = client.execute(method);
			String content = EntityUtils.toString(proxyResponse.getEntity());
			System.out.println("content:" + content);
			return content;
		} catch (Exception e) {
			// ExceptionUtil.logerErrorMes(loger, e);
		}

		return null;
	}

	/**
	 * Get XML String
	 *
	 * @return XML-Formed string
	 */
	public String getXMLString() {
		// A StringBuffer Object
		StringBuffer sb = new StringBuffer();
		sb.append(XML_HEADER);
		sb.append("<AastraIPPhoneInputScreen type=\"string\">");
		sb.append("<Title>Hello world!</Title>");
		sb.append("<Prompt>Enter value</Prompt>");
		sb.append("<URL>http://localhost/xmlserver/test.do</URL>");
		sb.append("<Parameter>value</Parameter>");
		sb.append("<Default></Default>");
		sb.append("</AastraIPPhoneInputScreen>");
		// return to String Formed
		return sb.toString();
	}

}
